import PropTypes from 'prop-types';
import React from 'react';
import { message, Spin } from 'antd';
import { API_HOST } from 'Constants/config';
import Api from 'Utils/api';
import './index.scss';

/**
 * 视频上传组件
 * 需要Form包裹来使用
 */
class UploadVideo extends React.PureComponent {
  static propTypes = {
    value: PropTypes.number,
    onChange: PropTypes.func,
  }
  static defaultProps = {
    value: 0,
    onChange: () => {},
  }
  constructor(props) {
    super(props);
    this.state = {
      resourceId: props.value,
      loading: false
    };
    this.uploadInput = undefined;
    this.videoRef = undefined;
    this.uploadVideo = ::this.uploadVideo;
  }
  componentWillReceiveProps(nextProps) {
    this.setState({ resourceId: nextProps.value });
  }
  uploadVideo() {
    const { onChange } = this.props;
    const file = this.uploadInput.files[0];
    if (!file) {
      return;
    }
    this.setState({
      loading: true
    });
    const formData = new window.FormData();
    formData.append('upload_file', file);
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/files',
      noHeader: true,
      data: formData,
      success: (json) => {
        self.setState({ resourceId: json.id, loading: false }, () => {
          onChange(json.id);
          if (this.videoRef) {
            this.videoRef.src = `${API_HOST}/files/${json.id}`;
          }
        });
      },
      error: (msg) => {
        message.error(msg);
        this.setState({
          loading: false
        });
      },
    });
    api.run();
  }
  render() {
    const { resourceId, loading } = this.state;
    return (
      <div className="upload-video-container">
        <input
          ref={(ref) => { this.uploadInput = ref; }}
          type="file"
          accept="video/*"
          onChange={this.uploadVideo.bind(this)}
        />
        {
          loading ? <Spin /> : ''
        }
        <img src="images/dispatch/icon_add.png" alt="添加" />
        {resourceId > 0 &&
          <div className="video-wrap">
            <video
              ref={(ref) => { this.videoRef = ref; }}
              controls
              preload
              autoPlay
            >
              <source src={`${API_HOST}/files/${resourceId}`} type="video/webm" />
            </video>
          </div>
        }
      </div>
    );
  }
}

export default UploadVideo;
